﻿using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace AccountManager
{
    public class Constant
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
    public class Content
    {
        public bool UseConstant { get; set; }
        public string Value { get; set; }
    }
    public class Account
    {
        public string Key { get; set; }
        public List<Content> Contents = new List<Content>();
    }
    public class Manager
    {
        private Dictionary<string, Account> Accounts;
        private Dictionary<string, Constant> Constants;
        //private JavaScriptSerializer js = new JavaScriptSerializer();what the fuck this stupid library???
        private string m_accounts_path, m_constants_path;
        public Manager(string AccountsPath = "Accounts.json", string ConstantsPath = "Constants.json")
        {
            m_accounts_path = AccountsPath;
            m_constants_path = ConstantsPath;
            if (!File.Exists(AccountsPath))
                Accounts = new Dictionary<string, Account>();
            else
                Accounts = JsonConvert.DeserializeObject<Dictionary<string, Account>>(Decode(File.ReadAllText(AccountsPath)));
            if (!File.Exists(ConstantsPath))
                Constants = new Dictionary<string, Constant>();
            else
                Constants = JsonConvert.DeserializeObject<Dictionary<string, Constant>>(Decode(File.ReadAllText(ConstantsPath)));

        }
        ~Manager()
        {
            File.WriteAllText(m_accounts_path, Encode(JsonConvert.SerializeObject(Accounts)));
            File.WriteAllText(m_constants_path, Encode(JsonConvert.SerializeObject(Constants)));
        }
        public Dictionary<string, Account> GetAccounts()
        {
            return Accounts;
        }
        public Dictionary<string, Constant> GetConstants()
        {
            return Constants;
        }
        public bool AddConstant(string Key, string Value)
        {
            if (Constants.ContainsKey(Key))
            { Constants[Key] = new Constant() { Key = Key, Value = Value }; return true; }
            else
            { Constants.Add(Key, new Constant() { Key = Key, Value = Value }); return false; }
        }
        public bool AddAccount(Account Value)
        {
            if (Accounts.ContainsKey(Value.Key))
            { Accounts[Value.Key] = Value;return true; }
            else { Accounts.Add(Value.Key,Value);return false; }
        }
        private string Decode(string value)
        {
            return System.Text.Encoding.GetEncoding("utf-8").GetString(System.Convert.FromBase64String(value));
        }
        private string Encode(string value)
        {
            return System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("utf-8").GetBytes(value));
        }
    }
}
